#include "app_mqtt.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MQTTClient.h"
#include "log/log.h"

#define ADDRESS   "tcp://192.168.12.77:1883"
#define CLIENTID  "9b2c9c71-009a-4356-8176-c94abf7edf68" 
#define TOPIC_RTG    "remote_to_gateway"
#define TOPIC_GTR    "gateway_to_remote"
#define QOS     1
#define TIMEOUT   10000L

MQTTClient client;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
static MQTTClient_message pubmsg = MQTTClient_message_initializer;

static int (*recv_callback)(char *json) = NULL;

void delivered(void *context, MQTTClient_deliveryToken dt)
{
  log_debug("Message delivered successfully");
}

int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{

  int result = 0;

  if(recv_callback != NULL)
  {
    result = recv_callback((char *)message->payload) == 0 ? 1 : 0;
  }
  
  MQTTClient_freeMessage(&message);
  MQTTClient_free(topicName);
  return result;
}

void connlost(void *context, char *cause)
{
  log_error("Connection lost\n");
  log_error("     cause: %s\n", cause);
}

int app_mqtt_init(void)
{
    int rc = 0 ;

    // 1. 创建客户端对象
    if ((rc = MQTTClient_create(&client, ADDRESS, CLIENTID,
    MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTCLIENT_SUCCESS)
  {
    log_error("MQTTClient_create failed");
    rc = EXIT_FAILURE;
    goto exit;
  }

    // 2.设置回调函数
    if ((rc = MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered)) != MQTTCLIENT_SUCCESS)
  {
    log_error("MQTTClient_setCallbacks failed");
    rc = EXIT_FAILURE;
    MQTTClient_destroy(&client);
    goto exit;
  }

    // 3. 连接服务器
    if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
  {
    log_error("MQTTClient_connect failed");
    rc = EXIT_FAILURE;
    MQTTClient_destroy(&client);
    goto exit;
  }

    // 4. 订阅主题
    if ((rc = MQTTClient_subscribe(client, TOPIC_RTG, QOS)) != MQTTCLIENT_SUCCESS)
  {
    log_error("MQTTClient_subscribe failed");
    MQTTClient_disconnect(client,1000);
    MQTTClient_destroy(&client);
    rc = EXIT_FAILURE;
    goto exit;
  }

    exit:
    return rc;
}

void app_mqtt_close(void)
{
    MQTTClient_unsubscribe(client, TOPIC_RTG);
    MQTTClient_disconnect(client,1000);
    MQTTClient_destroy(&client);
}

int app_mqtt_send(char *json)
{
  pubmsg.payload = json;
  pubmsg.payloadlen = (int)strlen(json)+1;
  pubmsg.qos = QOS;
  if ((MQTTClient_publishMessage(client, TOPIC_GTR, &pubmsg, NULL)) != MQTTCLIENT_SUCCESS)
  {
    log_error("MQTTClient_publishMessage failed");
    return EXIT_FAILURE;
  }
}

void app_mqtt_registerRevCallback(int (*callback)(char *json))
{
    recv_callback = callback;
}
